package com.example.xunai.dto.response.system;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TokenUsageResponse {
    private Long userId;
    private LocalDate startDate;
    private LocalDate endDate;
    private Integer totalInputTokens;
    private Integer totalOutputTokens;
    private Integer totalTokens;
    private List<ModelUsage> modelStats;
    private Double costEstimation;
    private String period;

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ModelUsage {
        private String model;
        private Integer inputTokens;
        private Integer outputTokens;
        private Integer totalTokens;
        private Double percentage;
    }

    public static TokenUsageResponse of(Long userId, LocalDate startDate, LocalDate endDate,
                                        Integer totalInputTokens, Integer totalOutputTokens,
                                        List<ModelUsage> modelStats) {
        int totalTokens = totalInputTokens + totalOutputTokens;

        // 计算每个模型的百分比
        if (modelStats != null && totalTokens > 0) {
            for (ModelUsage usage : modelStats) {
                double percentage = (double) usage.getTotalTokens() / totalTokens * 100;
                usage.setPercentage(Math.round(percentage * 100.0) / 100.0);
            }
        }

        return TokenUsageResponse.builder()
                .userId(userId)
                .startDate(startDate)
                .endDate(endDate)
                .totalInputTokens(totalInputTokens)
                .totalOutputTokens(totalOutputTokens)
                .totalTokens(totalTokens)
                .modelStats(modelStats)
                .costEstimation(calculateCostEstimation(totalTokens))
                .period(generatePeriodString(startDate, endDate))
                .build();
    }

    private static Double calculateCostEstimation(Integer totalTokens) {
        // 简单的成本估算逻辑，可以根据实际模型成本调整
        if (totalTokens == null || totalTokens == 0) return 0.0;
        return Math.round((totalTokens * 0.00002) * 100.0) / 100.0; // 假设 $0.02 per 1K tokens
    }

    private static String generatePeriodString(LocalDate startDate, LocalDate endDate) {
        if (startDate.equals(endDate)) {
            return startDate.toString();
        }
        return startDate + " 至 " + endDate;
    }

    public Double getInputTokenPercentage() {
        if (totalTokens == null || totalTokens == 0) return 0.0;
        return Math.round((double) totalInputTokens / totalTokens * 10000.0) / 100.0;
    }

    public Double getOutputTokenPercentage() {
        if (totalTokens == null || totalTokens == 0) return 0.0;
        return Math.round((double) totalOutputTokens / totalTokens * 10000.0) / 100.0;
    }
}